<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:search-box>
      <SearchForm :form-config="formConfig" :form-data="searchlist" @search="search" />
    </template>
    <template v-if="type == 1" v-slot:btn-box>
      <div class="page-top__todo">
        <CommonBtn @click="showChooseDialog = true">导入</CommonBtn>
        <CommonBtn @click="reload">刷新</CommonBtn>
        <CommonBtn @click="add">添加</CommonBtn>
        <CommonBtn :disabled="!delActive" @click="del">删除</CommonBtn>
      </div>
    </template>
    <template v-slot:content>
      <div class="content-wrapper">
        <div class="left">
          <div class="title">选择设备类型</div>
          <div class="tree">
            <TypeTree @changeType="changeType" @updateEquModelArr="updateEquModelArr" />
          </div>
        </div>
        <div class="right">
          <el-table ref="equipStadingBookTable" v-loading="tableLoading" class="equip-stading-book-table" :data="tableData" stripe border height="calc(100% - 50px)" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="equipmentName" label="设备名称" width="100" />
            <el-table-column prop="equModelName" label="所属设备型号" width="150" />
            <el-table-column prop="produceDate" label="生产日期" width="150" />
            <el-table-column prop="sellByDate" label="质保期" />
            <el-table-column prop="warrantyDate" label="质保日期" />
            <el-table-column prop="statusText" label="状态">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                <el-switch v-model="scope.row.statusText" :disabled="scope.row.sourceMethod !== '0'" @change="changeStatus(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column v-if="type !== 2" prop="sourceMethodText" label="添加方式" />
            <el-table-column prop="operate" label="操作" width="200">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                <template v-if="type !== 1">
                  <el-button class="text-btn-cursor" type="text" size="small" @click="toShowPreImgs(scope.row)"> 查看设备图片 </el-button>
                </template>
                <template v-else>
                  <template>
                    <el-button v-if="scope.row.sourceMethod === '0'" class="text-btn-cursor" type="text" size="small" @click="edit(scope.row)"> 编辑设备信息 </el-button>
                    <el-button class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row.equipmentId)"> 删除 </el-button>
                  </template>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
        </div>
      </div>
      <AddEditDialog v-model="showAddEditDialog" :equ-model-arr="equModelArr" :select-code="selectCode" @reflash="getEquList" />
      <CompleteInfoDialog v-model="showCompleteInfoDialog" :equ-model-arr="equModelArr" :edit-object="selectedEqu" @reflash="getEquList" />
      <ChooseDialog v-if="type === 1" v-model="showChooseDialog" @sub="importSub" />
      <FilePreview v-model="showImagesDialog" :file="preImgList" :loading="showImagesDialogLoading" />
    </template>
  </BaseMainSlot>
</template>
<script>
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot';
import SearchForm from '@/components/searchForm';
import TypeTree from './components/type-tree';
import EquipmentApi from '@/api/processing-management/equip-manage/equipment/index';
import EquipStandingBookApi from '@/api/processing-management/equip-manage/equip-standing-book';
import AddEditDialog from './components/add-edit-dialog.vue';
import CompleteInfoDialog from './components/complete-info-dialog.vue';
import ChooseDialog from './components/choose-dialog.vue';
import Pagination from '@/components/Pagination';
import { formItems, tableLabel, tableOption, dialogFormItems, filterItem, enumList } from './viewConfig';
import documentApi from '@/api/document';
import FilePreview from '@/components/FilePreview/index';
export default {
  name: 'EquipStadingBook',
  inject: ['reload'],
  components: {
    BaseMainSlot,
    SearchForm,
    TypeTree,
    Pagination,
    AddEditDialog,
    CompleteInfoDialog,
    ChooseDialog,
    FilePreview
  },
  props: {
    type: {
      type: Number,
      default: 1 // 1 默认  2 从总设备管理导入 2 自己作为列表导出
    }
  },
  data() {
    return {
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      loading: false,
      formItems,
      tableLabel,
      tableOption,
      dialogFormItems,
      filterItem,
      enumList,
      formConfig: [
        {
          label: '设备名称',
          prop: 'equipmentName',
          type: 'input'
        },
        {
          label: '生产日期',
          prop: 'produceDate',
          type: 'date'
        },
        {
          label: '质保期',
          prop: 'sellByDate',
          type: 'input'
        },
        {
          label: '质保日期',
          prop: 'warrantyDate',
          type: 'date'
        },
        {
          label: '状态',
          prop: 'status',
          type: 'select',
          options: [
            {
              label: '启用',
              value: 'ENABLE'
            },
            {
              label: '废弃',
              value: 'DISCARD'
            }
          ],
          optionKey: { label: 'label', value: 'value' }
        }
      ],
      searchlist: {},
      showAddEditDialog: false,
      equModelArr: [],
      selectCode: null,
      selectedEqu: null,
      tableData: [],
      showCompleteInfoDialog: false,
      multipleSelection: [], // 选中的行
      showChooseDialog: false,
      statusMap: {
        启用: 'ENABLE',
        废弃: 'DISCARD',
        维修中: 'REPAIRING',
        禁用: 'DISABLE'
      },
      showImagesDialog: false,
      preImgList: [],
      moduleType: 'PROCESSTEST',
      showImagesDialogLoading: false,
      delActive: false
    };
  },
  methods: {
    search() {
      this.getEquList();
    },
    async getEquList(equipmentTypeCode = null, queryType = null) {
      if (queryType) {
        this.currentPage = 1;
      }
      if (!equipmentTypeCode) {
        equipmentTypeCode = this.selectCode;
      }
      this.selectCode = equipmentTypeCode;
      this.tableLoading = true;
      const res = await this.getList();
      this.tableLoading = false;
      this.totalSize = res.data.totalElements;
      this.formateData(res.data.content);
      if (res.data.content.length === 0 && this.currentPage !== 1) {
        this.currentPage--;
        this.getEquList();
      }
    },
    async getList() {
      const { type, currentPage, pageSize, selectCode } = this;
      let res;
      const paylod = {
        page: currentPage,
        size: pageSize,
        entity: {
          equipmentTypeCode: selectCode,
          ...this.searchlist
        }
      };
      if (type === 1 || type === 3) {
        res = await EquipmentApi.queryPageByCondition(paylod);
      }
      if (type === 2) {
        res = EquipStandingBookApi.queryPageList(paylod);
      }
      return res;
    },
    formateData(data) {
      const { type, statusMap, selectCode, pageSize } = this;
      this.tableData = this.$utils.addblankmet(
        data.map(i => {
          if (type === 2) {
            i.statusText = statusMap[i.status] === 'ENABLE';
          } else {
            i.statusText = i.status === 'ENABLE';
          }
          i.sourceMethodText = i.sourceMethod === '0' ? '自行创建' : '库中导入';
          i.equModelName = this.findEquName(i.equModelCode);
          i.equipmentTypeCode = selectCode;
          return i;
        }),
        pageSize
      );
    },
    updateEquModelArr(data) {
      this.equModelArr = data;
    },
    add() {
      this.showAddEditDialog = true;
    },
    edit(item) {
      this.selectedEqu = JSON.parse(JSON.stringify(item));
      this.showCompleteInfoDialog = true;
    },
    del() {
      this.handleDelete(this.multipleSelection);
    },
    handleDelete(no) {
      let list = [no];
      if (no instanceof Array) {
        list = no.map(i => i.equipmentId);
      }
      this.$confirm('是否确认删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          EquipmentApi.delEquipments({ equipmentIdList: list }).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功');
              this.getEquList();
            }
          });
        })
        .catch(action => {});
    },
    findEquName(code) {
      const find = this.equModelArr.find(i => i.equModelCode === code);
      return find ? find.modelName : '';
    },
    changePageSize(v) {
      this.pageSize = v;
      this.getEquList();
    },
    changeCurrentPage(v) {
      this.currentPage = v;
      this.getEquList();
    },
    handleSelectionChange(v) {
      this.multipleSelection = v;
      const { type } = this;
      if (type !== 1) {
        this.$emit('changeSelect', v);
      }
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    changeType(v) {
      this.selectCode = v;
      this.getEquList(null, 'reflash');
    },
    changeStatus(item) {
      const tempData = JSON.parse(JSON.stringify(item));
      tempData.status = tempData.statusText ? 'ENABLE' : 'DISCARD';
      EquipmentApi.editEquipment(tempData);
    },
    // 导入设备
    importSub(items) {
      const { statusMap } = this;
      const list = items.map(i => {
        delete i.statusText;
        delete i.sourceMethodText;
        delete i.equModelName;
        i.status = statusMap[i.status];
        return i;
      });
      EquipmentApi.importEquipment(list).then(res => {
        if (res.code === 1) {
          this.$message.success('添加成功');
          this.getEquList();
          this.showChooseDialog = false;
        }
      });
    },
    clearSelect() {
      this.$refs.equipStadingBookTable.clearSelection();
      this.multipleSelection = [];
    },
    toShowPreImgs(row) {
      this.preImgList = [];
      this.showImagesDialog = true;
      this.showImagesDialogLoading = true;
      documentApi
        .queryPictureList(row.equipmentCode)
        .then(res => {
          if (res.code === 1) {
            const list = res.data;
            this.preImgList = list.map(i => {
              return {
                name: i.pictureName,
                url: `data:image/png;base64,${i.pictureData}`
              };
            });
            if (this.preImgList.length === 0) {
              this.$message.warning('暂无图片');
              return false;
            }
          }
        })
        .finally(() => {
          this.showImagesDialogLoading = false;
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.content-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  .left {
    width: 25%;
    -ms-flex-negative: 0;
    flex-shrink: 0;
    height: 100%;
    padding: 10px;
    background-color: #074052;
    .title {
      width: 100%;
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: 600;
      text-align: center;
      border-bottom: #fff dashed 1px;
    }
    .tree {
      width: 100%;
      height: calc(100% - 21px);
    }
  }
  .right {
    width: 75%;
    padding-left: 10px;
    box-sizing: border-box;
  }
}
</style>
